const fs = require('fs');
const pdfConverter = require('pdf-to-png-converter');
const path = require('path');
const pdf2image = require('pdf2image');
const inputFolder = './PDFS'; // PDF文件所在的文件夹
const outputFolder = './images'; // 转换后的PNG文件存放的文件夹

fs.readdir(inputFolder, async (err, files) => {
  if (err) {
    console.error('读取文件夹失败：', err);
    return;
  }
  const dimensArray = arrayToDimens(files);
  const dimensLenth = dimensArray.length;
  for (let index = 0; index < dimensLenth; index++) {
    console.log(`第${index + 1}轮解析开始 --- 文件组`, dimensArray[index]);
    await pdfToPngSync(dimensArray[index]);
  }
});

// 异步的解析pdf方法 - 同步调用
function pdfToPngSync(files) {
  const resArr = [];
  return new Promise((resolve, reject) => {
    files.forEach(async (file, index) => {
      if (path.extname(file).toLowerCase() === '.pdf') {
        const pdfPath = path.join(inputFolder, file);
        const outputPath = path.join(outputFolder, path.basename(file, '.pdf'));
        console.log(file, '开始解析.....');
        const pngPages = await pdfToPng(pdfPath, outputPath);
        resArr.push(pngPages);
        if (resArr.length === files.length) {
          resolve();
        }
      }
    });
  });
}
// 同步的解析pdf方法 - 异步调用
async function pdfToPng(pdfPath, outputFolder) {
  let pngPages = await pdfConverter.pdfToPng(
    pdfPath, // The function accepts PDF file path or a Buffer
    {
      disableFontFace: false, // When `false`, fonts will be rendered using a built-in font renderer that constructs the glyphs with primitive path commands. Default value is true.
      useSystemFonts: false, // When `true`, fonts that aren't embedded in the PDF document will fallback to a system font. Default value is false.
      enableXfa: false, // Render Xfa forms if any. Default value is false.
      viewportScale: 1, // The desired scale of PNG viewport. Default value is 1.0.
      outputFolder: outputFolder, // Folder to write output PNG files. If not specified, PNG output will be available only as a Buffer content, without saving to a file.
      outputFileMask: '', // Output filename mask. Default value is 'buffer'.
      // pdfFilePassword: '$pa$word', // Password for encrypted PDF.
      // pagesToProcess: [1, 3, 11], // Subset of pages to convert (first page = 1), other pages will be skipped if specified.
      strictPagesToProcess: false, // When `true`, will throw an error if specified page number in pagesToProcess is invalid, otherwise will skip invalid page. Default value is false.
      verbosityLevel: 0, // Verbosity level. ERRORS: 0, WARNINGS: 1, INFOS: 5. Default value is 0.
    }
  );
  pngPages = null;
  console.log(outputFolder, '解析完成！！！！');
  return "";
}

// 一维数组转换二维数组(10个一组)
function arrayToDimens(array, length = 10) {
  let result = [];
  let temp = [];
  array.forEach((item, index) => {
    temp.push(item);
    // 长度到达5,那么入组
    if (temp.length === length || index == array.length - 1) {
      result.push(temp);
      temp = [];
    }
  });
  return result;
}
